var express = require('express');
var router = express.Router();
var { Myuser } = require("../utils/model")
var { keys, aesEncrypt } = require("../utils");
/* GET users listing. */



router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});



//注册
router.post("/register", (req, res) => {
  //  res.send("登录-success--register")
  const body = req.body;
  Myuser.findOne({ username: body.username }).then(data => {
    if (data) {
      res.send(`<script>alert('用户名已经存在,请重新注册');window.location.href='/register' </script>`)
    } else {
      body.time = new Date();
      Myuser.insertMany(body)
        .then(result => {
          console.log(result)
          res.send(`<script>alert('注册成功,请马上登录');window.location.href='/login?username=${aesEncrypt(body.username, keys)}'</script>`)
        })
    }
  })
  //  res.render("register")
})

//登录
router.post("/login", (req, res) => {
  //  res.send("登录-success--login")
  var body = req.body;
  Myuser.findOne({ username: body.username }).then(result => {
    if (result) {
      if (result.userpwd == body.userpwd) {
        console.log(req.session);

        req.session.username = body.username;
        req.session.password = body.password;
        res.redirect("/");
      } else {
        console.log("error")
      }
    } else {
      console.log("用户名密码不正确")
    }
  })
})



// 动态路由   :type  表示参数  
router.get("/mav/:tpye", (req, res) => {
  res.json({
    msg: "获取电影数据成功",
    code: 200,
    result: null,
    params: req.params
  })
})


router.post("/getpost", function (req, res) {
  res.json({
    msg: "post requset",
    code: 200,
    resull: null,
  })
})
module.exports = router;
